<template>
	<view style="border-top: 1rpx solid #f8f8f8;">
		<!-- 评论列表 -->
		<template v-if="dataList && dataList.length">
			<view class="c_comment" v-for="(comment, commentIndex) in dataList" :key="comment.id">
				<!-- 一级评论 -->
				<CommonComp :data="comment" :one-level="true" @avatarClick="handleAvatarClick"
					@likeClick="() => handleLikeClick(comment, commentIndex)"
					@replyClick="() => handleReplyClick(comment, commentIndex)"
					@deleteClick="() => handleDeleteClick(comment, commentIndex)" />

				<!-- 二级评论 -->
				<view class="children_item" v-if="comment.children && comment.children.length">
					<CommonComp v-for="(childComment, childIndex) in comment.childrenShow" :key="childComment.id"
						:data="childComment" :pData="comment" @avatarClick="handleAvatarClick"
						@likeClick="() => handleChildLikeClick(comment, commentIndex, childComment, childIndex)"
						@replyClick="() => handleChildReplyClick(comment, commentIndex, childComment, childIndex)"
						@deleteClick="() => handleChildDeleteClick(comment, commentIndex, childComment, childIndex)" />

					<!-- 展开折叠的二级评论 -->
					<view class="expand_reply" v-if="shouldShowExpand(comment)"
						@tap="() => expandReplies(comment, commentIndex)">
						<span class="txt">
							展开{{ comment.children.length - comment.childrenShow.length }}条回复
						</span>
						<uni-icons type="down" size="24" color="#007aff"></uni-icons>
					</view>
				</view>
			</view>
		</template>

		<!-- 空评论状态 -->
		<view class="empty_box" v-else>
			<uni-icons type="chatboxes" size="36" color="#c0c0c0"></uni-icons>
			<view>
				<span class="txt"> 这里是一片荒草地, </span>
				<span class="txt click" @click="createNewComment">说点什么...</span>
			</view>
		</view>

		<!-- 评论弹窗遮罩层 -->
		<view class="popup-mask" v-if="isShowComment" @tap="cancelComment"></view>

		<!-- 评论弹窗 -->
		<view class="c_popup_box" v-if="isShowComment">
			<!-- 关闭按钮 -->
			<view class="popup-close" @tap="cancelComment">
				<u-icon name="close" size="20" color="#999"></u-icon>
			</view>

			<view class="reply_text">
				<template v-if="isReplyMode">
					<span class="text_aid">回复给</span>
					<span class="text_main">{{ getReplyTargetName() }}</span>
				</template>
				<span v-else class="text_main">发表新评论</span>
			</view>

			<view class="comment-content">
				<view class="text_area">
					<u-input :placeholder="commentPlaceholder" :focus="focus" border="surround" v-model="commentValue"
						maxlength="300" @keyboardheightchange="handleKeyboardHeightChange"></u-input>
				</view>
				<view class="send_btn" @tap="sendComment">发送</view>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<uni-popup ref="delPopupRef" type="dialog">
			<uni-popup-dialog mode="base" title="" content="确定删除这条评论吗?" :before-close="true" @close="closeDeleteDialog"
				@confirm="confirmDelete"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import CommonComp from "./componets/common";

	export default {
		name: "XJComment",
		components: {
			CommonComp
		},
		props: {
			userInfo: {
				type: Object,
				default: () => ({})
			},
			tableData: {
				type: Array,
				default: () => []
			},
			tableTotal: {
				type: Number,
				default: 0
			},
			deleteMode: {
				type: String,
				default: "all"
			}
		},
		data() {
			return {
				dataList: [],
				replyTarget: null, // 回复目标
				isNewComment: false,
				focus: false,
				commentValue: "",
				commentPlaceholder: "说点什么...",
				deleteTarget: null, // 删除目标
				isShowComment: false
			};
		},
		computed: {
			isReplyMode() {
				return this.replyTarget !== null && !this.isNewComment;
			}
		},
		watch: {
			tableData: {
				handler(newVal) {
					if (newVal.length !== this.dataList.length) {
						this.dataList = this.transformToTree(newVal);
					}
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			// 键盘高度变化处理
			handleKeyboardHeightChange(e) {
				console.log(e);
			},

			// 将扁平数据转换为树形结构
			transformToTree(data) {
				const newData = JSON.parse(JSON.stringify(data));
				const result = [];
				const map = {};

				// 建立映射关系并标记所有者
				newData.forEach((item) => {
					item.owner = item.user_id === this.userInfo.id;
					map[item.id] = item;
				});

				// 构建树形结构
				newData.forEach((item) => {
					const parent = map[item.parent_id];
					if (parent) {
						// 子评论
						if (!parent.children) {
							parent.children = [];
						}
						parent.children.push(item);

						// 初始化显示的子评论（只显示第一个）
						if (parent.children.length === 1) {
							parent.childrenShow = [item];
						}
					} else {
						// 顶级评论
						result.push(item);
					}
				});

				return result;
			},

			// 头像点击处理
			handleAvatarClick(userId) {
				this.$emit("avatarFun", userId);
			},

			// 点赞状态切换
			toggleLikeStatus(item) {
				item.is_like = !item.is_like;
				item.like_count = item.is_like ? Number(item.like_count) + 1 : Number(item.like_count) - 1;
			},

			// 一级评论点赞
			handleLikeClick(comment, commentIndex) {
				this.toggleLikeStatus(comment);
				this.$emit("likeFun", comment, (res) => {
					this.toggleLikeStatus(comment);
				});
			},

			// 二级评论点赞
			handleChildLikeClick(parentComment, parentIndex, childComment, childIndex) {
				this.toggleLikeStatus(childComment);
				this.$emit("likeFun", childComment, (res) => {
					this.toggleLikeStatus(childComment);
				});
			},

			// 一级评论回复
			handleReplyClick(comment, commentIndex) {
				this.replyTarget = {
					parentComment: comment,
					parentIndex: commentIndex
				};
				this.openCommentDialog();
			},

			// 二级评论回复
			handleChildReplyClick(parentComment, parentIndex, childComment, childIndex) {
				this.replyTarget = {
					parentComment: parentComment,
					parentIndex: parentIndex,
					childComment: childComment,
					childIndex: childIndex
				};
				this.openCommentDialog();
			},

			// 打开评论对话框
			openCommentDialog() {
				this.isShowComment = true;
				this.focus = true;
			},

			// 关闭评论对话框
			closeCommentDialog() {
				this.commentValue = "";
				this.replyTarget = null;
				this.isShowComment = false;
				this.isNewComment = false;
			},

			// 取消评论
			cancelComment() {
				this.closeCommentDialog();
			},

			// 创建新评论
			createNewComment() {
				this.isNewComment = true;
				this.openCommentDialog();
			},

			// 获取回复目标名称
			getReplyTargetName() {
				if (!this.replyTarget) return "";

				if (this.replyTarget.childComment) {
					return this.replyTarget.childComment.user_name;
				}
				return this.replyTarget.parentComment.user_name;
			},

			// 发送评论
			sendComment() {
				const commentParams = this.buildCommentParams();

				uni.showLoading({
					title: "正在发送",
					mask: true
				});

				this.$emit("replyFun", {
					params: commentParams
				}, (res) => {
					uni.hideLoading();
					this.handleCommentSuccess(res, commentParams);
				});
			},

			// 构建评论参数
			buildCommentParams() {
				let params = {};

				if (this.isNewComment) {
					// 新评论
					params = {
						id: Math.random(),
						parent_id: null,
						reply_id: null,
						reply_name: null,
						user_id: null
					};
				} else {
					// 回复评论
					const {
						parentComment,
						childComment
					} = this.replyTarget;
					const targetComment = childComment || parentComment;

					params = {
						id: Math.random(),
						parent_id: parentComment.parent_id || parentComment.id,
						reply_id: targetComment.user_id,
						reply_name: targetComment.user_name,
						user_id: targetComment.user_id
					};
				}

				// 公共参数
				return {
					...params,
					user_name: this.$store.state.userInfo.nickName,
					user_avatar: this.$store.state.userInfo.avatar,
					user_content: this.commentValue,
					is_like: false,
					like_count: 0,
					create_time: "刚刚",
					owner: this.$store.state.userInfo.userId == this.userInfo.id,
				};
			},

			// 处理评论发送成功
			handleCommentSuccess(res, params) {
				// 更新ID
				params.id = res.id;

				if (this.isNewComment) {
					// 添加新评论
					this.dataList.push(params);
				} else {
					// 添加回复
					const {
						parentIndex
					} = this.replyTarget;
					const parentComment = this.dataList[parentIndex];

					// 添加到children
					if (!parentComment.children) {
						parentComment.children = [];
					}
					parentComment.children.push(params);

					// 添加到childrenShow（用于显示）
					if (!parentComment.childrenShow) {
						parentComment.childrenShow = [];
					}

					// 如果childrenShow长度比children少，说明有折叠
					if (parentComment.children.length === parentComment.childrenShow.length + 1) {
						parentComment.childrenShow.push(params);
					}
				}

				// 更新总数
				this.$emit("update:tableTotal", this.tableTotal + 1);

				// 关闭评论框
				this.$nextTick(() => {
					this.closeCommentDialog();
				});
			},

			// 一级评论删除
			handleDeleteClick(comment, commentIndex) {
				this.deleteTarget = {
					parentComment: comment,
					parentIndex: commentIndex
				};
				this.openDeleteDialog();
			},

			// 二级评论删除
			handleChildDeleteClick(parentComment, parentIndex, childComment, childIndex) {
				this.deleteTarget = {
					parentComment: parentComment,
					parentIndex: parentIndex,
					childComment: childComment,
					childIndex: childIndex
				};
				this.openDeleteDialog();
			},

			// 打开删除确认对话框
			openDeleteDialog() {
				this.$refs.delPopupRef.open();
			},

			// 关闭删除确认对话框
			closeDeleteDialog() {
				this.deleteTarget = null;
				this.$refs.delPopupRef.close();
			},

			// 确认删除
			confirmDelete() {
				if (!this.deleteTarget) return;

				const {
					parentComment,
					parentIndex,
					childComment,
					childIndex
				} = this.deleteTarget;

				uni.showLoading({
					title: "正在删除",
					mask: true
				});

				if (childComment) {
					// 删除子评论
					this.deleteChildComment(parentComment, childIndex);
				} else {
					// 删除父评论
					this.deleteParentComment(parentComment, parentIndex);
				}

				this.closeDeleteDialog();
			},

			// 删除子评论
			deleteChildComment(parentComment, childIndex) {
				this.$emit("deleteFun", {
					params: [parentComment.children[childIndex].id]
				}, (res) => {
					uni.hideLoading();
					this.$emit("update:tableTotal", this.tableTotal - 1);
					parentComment.children.splice(childIndex, 1);
					parentComment.childrenShow.splice(childIndex, 1);
				});
			},

			// 删除父评论
			deleteParentComment(parentComment, parentIndex) {
				if (parentComment.children && parentComment.children.length) {
					// 有子评论的情况
					this.deleteParentWithChildren(parentComment, parentIndex);
				} else {
					// 无子评论的情况
					this.deleteParentWithoutChildren(parentComment, parentIndex);
				}
			},

			// 删除有子评论的父评论
			deleteParentWithChildren(parentComment, parentIndex) {
				switch (this.deleteMode) {
					case "bind":
						// 仅删除内容
						parentComment.user_content = "当前评论内容已被移除";
						uni.hideLoading();
						break;
					case "only":
						// 仅删除父评论
						this.$emit("deleteFun", {
							mode: this.deleteMode,
							params: [parentComment.id]
						}, (res) => {
							uni.hideLoading();
							this.$emit("update:tableTotal", this.tableTotal - parentComment.children.length + 1);
							this.dataList.splice(parentIndex, 1);
						});
						break;
					default:
						// 删除父评论和所有子评论
						const deleteIds = [parentComment.id, ...parentComment.children.map(child => child.id)];
						this.$emit("deleteFun", {
							params: deleteIds,
							mode: this.deleteMode
						}, (res) => {
							uni.hideLoading();
							this.$emit("update:tableTotal", this.tableTotal - parentComment.children.length - 1);
							this.dataList.splice(parentIndex, 1);
						});
						break;
				}
			},

			// 删除无子评论的父评论
			deleteParentWithoutChildren(parentComment, parentIndex) {
				this.$emit("deleteFun", {
					params: [parentComment.id]
				}, (res) => {
					uni.hideLoading();
					this.$emit("update:tableTotal", this.tableTotal - 1);
					this.dataList.splice(parentIndex, 1);
				});
			},

			// 是否显示展开按钮
			shouldShowExpand(comment) {
				return comment.childrenShow &&
					comment.childrenShow.length &&
					comment.children.length > comment.childrenShow.length;
			},

			// 展开更多回复
			expandReplies(comment, commentIndex) {
				const currentShowLength = this.dataList[commentIndex].childrenShow.length;
				const remainingItems = this.dataList[commentIndex].children.slice(
					currentShowLength,
					currentShowLength + 6
				);
				this.dataList[commentIndex].childrenShow.push(...remainingItems);
			}
		}
	};
</script>

<style lang="scss" scoped>
	////////////////////////
	.center {
		display: flex;
		align-items: center;
	}

	////////////////////////
	.c_total {
		padding: 20rpx 30rpx 0 0;
		font-size: 28rpx;
	}

	.empty_box {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		padding: 150rpx 10rpx;
		font-size: 28rpx;

		.txt {
			color: $uni-text-color-disable;
		}

		.click {
			color: #FFAE1A;
		}
	}

	.c_comment {
		padding: 20rpx 0;
		font-size: 28rpx;

		.children_item {
			padding: 20rpx 0;
			margin-top: 10rpx;
			margin-left: 80rpx;

			.expand_reply {
				margin-top: 10rpx;
				margin-left: 80rpx;

				.txt {
					font-weight: 600;
					color: $uni-color-primary;
				}
			}
		}
	}

	// 添加遮罩层样式
	.popup-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		z-index: 998;
	}

	.c_popup_box {
		background-color: #fff;
		position: fixed;
		bottom: 200rpx;
		padding-bottom: 20rpx;
		left: 0;
		right: 0;
		z-index: 999;

		// 添加关闭按钮样式
		.popup-close {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			padding: 10rpx;
			z-index: 1000;
		}

		.reply_text {
			@extend .center;
			padding: 20rpx 20rpx 0 20rpx;
			font-size: 26rpx;

			.text_aid {
				color: $uni-text-color-grey;
				margin-right: 5rpx;
			}
		}

		.comment-content {
			margin-bottom: 20rpx;
			@extend .center;

			.text_area {
				flex: 1;
				padding: 20rpx;
			}

			.send_btn {
				@extend .center;
				justify-content: center;
				width: 120rpx;
				height: 60rpx;
				border-radius: 10rpx;
				font-size: 28rpx;
				color: #FFAE1A;
				margin-left: 20rpx;
				border: 1rpx solid #FFAE1A;
				margin-right: 20rpx;
			}
		}
	}
</style>